// @ts-nocheck
import {useState, useEffect} from 'react'
import {PageHeaderWrapper} from '@ant-design/pro-layout';
import {List, Avatar, Row, Col, Card, Checkbox, Tree, Space, Button, Popconfirm as Confirm, message} from 'antd'
import {useModel, Access} from 'umi'
import {queryRole, modifyRole} from '@/services/role'
import {page, operation} from '@/services/ant-design-pro/api'
import {remove, authority} from '@/tools/tool'

const Index = () => {
  const init = useModel('@@initialState');
  const {currentUser} = init.initialState
  const [data, setData] = useState([])
  const [pageData, setPage] = useState([])
  const [makeData, setMake] = useState([])
  const [makeFilter, setFilter] = useState([])
  const [defaultPage, setDefaultPage] = useState([])
  const [defaultMake, setDefaultMake] = useState([])
  const [index, setIndex] = useState(0)

  const getMakeData = (id: number) => {
    if (defaultPage.includes(id.toString())) {
      const list = makeData.filter(v => v.page_id === id)
      setFilter(list)
    } else {
      message.warning('请先勾选相关页面权限！').then()
      setFilter([])
    }
  }

  const getTreeData = (trees: any[], parentId: number, initPage) => {
    const tree: { title: any; key: any; children: any[]; }[] = []
    trees.forEach(v => {
      if (v.parent_id === parentId) {
        tree.push({
          title: <Space size={'large'}>
            <div> {v.name}</div>
            {v.parent_id !== 0 && <a onClick={() => getMakeData(v.id)}>分配操作权限</a>}
          </Space>,
          key: v.id.toString(),
          children: getTreeData(trees, v.id, initPage)
        })
      }
    })
    return tree
  }
  useEffect(() => {
    queryRole({}).then(res => {
      setData(res.data)
    })
    page({}).then(res => {
      setPage(res.data)
    })
    operation({}).then(res => {
      setMake(res.data)
    })

  }, [])

  // eslint-disable-next-line @typescript-eslint/no-shadow
  const getPage = (checked: boolean, page: object) => {
    setIndex(checked ? page.id : 0)
    if (checked) {
      const keys = page.page_auth_filter ? page.page_auth_filter.split(',') : []
      const makes = page.operation_auth ? page.operation_auth.split(',') : []
      setDefaultPage(keys)
      setDefaultMake(makes)
      console.log(keys)
    } else {
      setDefaultPage([])
      setDefaultMake([])
    }
  }

  const changeMake = (checked: boolean, id: string) => {
    let makes
    if (checked) {
      makes = defaultMake.concat(id)
    } else {
      makes = remove(defaultMake, id)
    }
    setDefaultMake(makes)
  }
  const saveAuth = () => {
    let list = defaultPage
    pageData.forEach(v => {
      if (defaultPage.includes(v.page_id.toString())) {
        if (v.parent_id.toString() !== '0') {
          list.push(v.parent_id.toString())
        }
      }
    })
    list = Array.from(new Set(list))
    const body = {
      role_id: index,
      page_auth: list.join(","),
      operation_auth: defaultMake.join(",")
    }
    modifyRole(body).then(res => {
      if (res.status === 200) {
        message.success('保存成功，请重新登录！').then()
        // eslint-disable-next-line @typescript-eslint/no-shadow
        queryRole({}).then(res => {
          setData(res.data)
        })
        setIndex(0)
        setDefaultMake([])
        setDefaultPage([])
      } else {
        message.error('保存失败').then()
      }
    })

  }
  // @ts-ignore
  return (
    <PageHeaderWrapper>
      <Row gutter={16}>
        <Col className="gutter-row" span={6}>
          <Card title={'角色选择'} style={{height: '500px'}}>
            <List
              itemLayout="horizontal"
              dataSource={data}
              renderItem={item => (
                <List.Item>
                  <div>
                    <Avatar src="https://joeschmoe.io/api/v1/jon"/>
                    &ensp;&ensp;
                    <span style={{fontWeight: 'bold'}}>{item.name}</span>
                  </div>
                  <Checkbox checked={index === item.id}
                            onChange={(e) => getPage(e.target.checked, item)}/>
                </List.Item>
              )}
            />
          </Card>
        </Col>
        <Col className="gutter-row" span={9}>
          <Card title={'页面权限'} style={{height: '500px',overflow:'hidden'}} >
            <div style={{height: '400px',overflowY:'scroll'}}>
              {pageData.length > 0 && <Tree
                onCheck={(e) => {
                  setDefaultPage(e);
                  console.log(e)
                }}
                checkable
                checkedKeys={defaultPage}
                defaultExpandAll
                // checkStrictly
                treeData={getTreeData(pageData, 0, defaultPage)}
              />}
            </div>
          </Card>
        </Col>
        <Col className="gutter-row" span={9}>
          <Card title={'操作权限'} style={{height: '500px',overflow:'hidden'}}
                extra={<Access accessible={index && authority('4', currentUser.operation)}><Confirm
                  title="确认保存当前角色的所有权限吗?"
                  okText="确认"
                  onConfirm={() => saveAuth()}
                  cancelText="取消"
                >
                  <Button type={'primary'}>全部保存</Button>
                </Confirm></Access>}>
            <List
              style={{height: '400px',overflowY:'scroll'}}
              itemLayout="horizontal"
              dataSource={makeFilter}
              renderItem={item => (
                <List.Item>
                  <div>
                    <span style={{fontWeight: 'bold'}}>{item.name}</span>
                  </div>
                  <Checkbox checked={defaultMake.includes(item.operation_id.toString())}
                            onChange={(e) => changeMake(e.target.checked, item.operation_id.toString())}/>
                </List.Item>
              )}
            />
          </Card>
        </Col>
      </Row>

    </PageHeaderWrapper>
  );
};

export default Index;
